<template>
    <div>
        <el-card class="!border-none" shadow="never">
            <el-button v-perms="['customerlist:add/edit']" type="primary" @click="handleInsert(rowId)">
                <template #icon>
                    <icon name="el-icon-Document" />
                </template>
                提交
            </el-button>
            <el-button v-perms="['customerlist:add/edit']" type="primary" @click="submit()">
                <template #icon>
                    <icon name="el-icon-FolderChecked" />
                </template>
                保存
            </el-button>
        </el-card>
        <el-card class="!border-none" style="margin-top: 20px;" shadow="never">
            <div>
                <el-form ref="formRef" :model="formData" label-width="200px" :rules="formRules" :inline="true" class="porjectFormRef">
                    <el-form-item label="项目名称" prop="projectName" class="w-[45%]">
                        <el-input v-model="formData.projectName" placeholder="请输入项目名称" />
                    </el-form-item>
                    <el-form-item label="项目关键要素" prop="projectKey" class="w-[45%]">
                        <el-input v-model="formData.projectKey" placeholder="请输入项目关键要素" type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" />
                    </el-form-item>
                    <el-form-item label="核心要素" prop="keyElement" class="w-[45%]">
                        <el-input v-model="formData.keyElement" placeholder="请输入核心要素" type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" />
                    </el-form-item>

                    <el-form-item class="w-[45%]" label="申报条件">
                        <el-button v-perms="['detail:add']" type="primary" @click="shengbao">
                            <template #icon>
                                <icon name="el-icon-Plus" />
                            </template>
                            选择申报条件
                        </el-button>
                        <div class="mt-2">
                            <el-tag v-for="(item, index) in formData.declarationConditions" :key="index" closable @close="removeCondition(item, index)" class="mr-2 tag-with-ellipsis" :title="item.andsqlName">
                                {{ item.andsqlName }}
                                <!-- {{item.declarationTypeId}} -->
                            </el-tag>
                        </div>
                    </el-form-item>
                    <el-form-item label="受理部门" prop="acceptanceDepartment" class="w-[45%]">
                        <el-input v-model="formData.acceptanceDepartment" />
                    </el-form-item>
                    <!-- <el-form-item label="申报时间" prop="declarationTime" class="w-[45%]">
                        <el-date-picker v-model="formData.declarationTime" type="datetime" placeholder="选择日期时间">
                        </el-date-picker>
                    </el-form-item> -->
                    <el-form-item label="申报时间" prop="declarationTime" class="w-[45%]">
                        <el-date-picker v-model="formData.declarationTime" type="daterange" value-format="YYYY-MM-DD" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" :size="size" />
                    </el-form-item>
                    <el-form-item label="资助额度" prop="amountSubsidy" class="w-[45%]">

                        <el-input-number v-model="formData.amountSubsidy" :min="1" />
                        &nbsp;&nbsp;万
                    </el-form-item>
                    <el-form-item label="三星条数" prop="ratingThree" class="w-[45%]">
                        <el-input-number v-model="formData.ratingThree" :min="1" :max="30" />
                    </el-form-item>

                    <el-form-item label="四星条数" prop="ratingFour" class="w-[45%]">
                        <el-input-number v-model="formData.ratingFour" :min="1" :max="30" />
                    </el-form-item>

                    <el-form-item label="五星条数" prop="ratingFive" class="w-[45%]">
                        <el-input-number v-model="formData.ratingFive" :min="1" :max="30" />
                    </el-form-item>
                </el-form>
            </div>
        </el-card>
        <!-- 列表弹窗 -->
        <el-dialog title="添加申报条件" v-model="addShow" width="70%" @close="handleClose" @open="handleOpen">
            <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true">
                <el-form-item label="申报类型" prop="typeId">
                    <el-select v-model="queryParams.typeId" filterable remote clearable reserve-keyword placeholder="请选择申报类型" style="width: 283px" :remote-method="remoteLocationMethod" :loading="loading">
                        <el-option v-for="item in declarationTypeData" :key="item.id" :label="item.typeName" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="申报条件" prop="acceptancerequirments">
                    <el-input class="w-[280px]" v-model="queryParams.acceptancerequirments" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="resetPage">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </el-form-item>
            </el-form>
            <!-- <el-table class="mt-4" size="large" v-loading="pager.loading"  ref="myTable" :data="pager.lists" v-model:selection="selectedRows"> -->
            <el-table class="mt-4" size="large" v-loading="pager.loading" :data="pager.lists" ref="myTable" v-model:selection="selectedRows" @selection-change="handleRows">
                <el-table-column type="selection" width="55" />
                <el-table-column label="编号" prop="id" min-width="50" />
                <el-table-column label="申报类型" prop="typeName" min-width="250" />
                <el-table-column label="符号" prop="symbol" min-width="80" />
                <el-table-column label="申报条件" prop="acceptancerequirments" min-width="100" />
                <el-table-column label="修改人" prop="modifier" min-width="100" />
                <el-table-column label="创建人" prop="creator" min-width="100" />
                <el-table-column label="创建时间" prop="createTime" min-width="100" />
                <el-table-column label="更新时间" prop="updateTime" min-width="100" />

            </el-table>
            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" />
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleClose">取消</el-button>
                    <el-button type="primary" @click="handleSubmit"> 确认 </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { detailEdit, detailAdd, detailDetail } from '@/api/detail'
import { DetailTypeDelete, DetailTypeLists, DetailTypeAdd, DetailTypeAddList } from '@/api/DetailType'
import { declarationTypeLists } from '@/api/declarationType'
import Popup from '@/components/popup/index.vue'
import type { PropType } from 'vue'
import { declarationDelete, declarationLists } from '@/api/declaration'
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'
import { useRoute } from 'vue-router';


const route = useRoute();
const rowId = route.query.id;
// const declarationConditionsList=ref([]);
const selectedRows = ref([])
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const addShow = ref(false)

const formData = reactive({
    id: '',
    projectName: '',
    declarationConditions: [] as any,
    projectKey: '',
    keyElement: '',
    ratingThree: '',
    ratingFour: '',
    ratingFive: '',
    acceptanceDepartment: '',
    declarationTime: '',
    declarationStart: '', // 开始日期
    declarationEnd: '',   // 结束日期
    amountSubsidy: ''
})

const formRules = {}

const handleInsert = async () => {
    if (formData.declarationTime && formData.declarationTime.length === 2) {
        formData.declarationStart = formData.declarationTime[0];  // 设置开始日期
        formData.declarationEnd = formData.declarationTime[1];    // 设置结束日期
    }
    const data: any = { ...formData }
    console.log('提交', data)
    rowId == null ? await detailAdd(data) : await detailEdit(data)
    feedback.msgSuccess('操作成功')
    emit('success')
}

const setFormData = async (data: Record<string, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const getDetail = async (rowId: any) => {
    const data = await detailDetail({
        id: rowId
    })
    // declarationConditionsList.value=data.declarationConditions;
    setFormData(data)
}
if (rowId) {
    getDetail(rowId)
}

const submit = () => {
    console.log("缓存的页面内容", JSON.stringify(formData));
    localStorage.setItem('formData', JSON.stringify(formData));
    feedback.msgSuccess('数据已保存！')
    emit('success')
};

onMounted(() => {
    const savedData = localStorage.getItem('formData');
    if (savedData) {
        Object.assign(formData, JSON.parse(savedData)); // 解析并赋值给表单数据
    }
});


defineExpose({
    open,
    setFormData

})

const showEdit = ref(false)
const queryParams = reactive({
    modifier: '',
    creator: '',
    code: '',
    acceptancerequirments: '',
    typeId: '',
})

const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: declarationLists,
    params: queryParams
})

const declarationTypeData = ref([]);
//获取申报类型
const paramsType = reactive({
    pageNo: 1,
    pageSize: 60,
    typeName: null
})
const getDeclarationType = async () => {
    try {
        await declarationTypeLists(paramsType).then((res) => {
            declarationTypeData.value = res.lists
            return declarationTypeData.value
        })
    } catch (error) {
        console.error('获取数据失败:', error);
    }
}
//搜索申报类型
const remoteLocationMethod = async (query) => {
    paramsType.typeName = query
    declarationTypeLists(paramsType).then((res) => {
        declarationTypeData.value = res.lists
        return declarationTypeData.value
    })
}

//移除已选择的某关系
const removeCondition = async (item: number, index: number) => {
    await feedback.confirm('确定要删除？');
    // const id=item.id;
    // await DetailTypeDelete({ id });
    formData.declarationConditions.splice(index, 1);
}
const myTable = ref(null)  // 表格的 ref

const shengbao = async () => {
    addShow.value = true
    nextTick(() => {
        // 重新选中之前选中的项
        // declarationConditionsList.value.forEach(row => {
        formData.declarationConditions.forEach(row => {
            console.log('选中', row)
            const existRow = pager.lists.find(item => item.id === row.declarationTypeId)
            if (existRow && myTable.value) {
                myTable.value.toggleRowSelection(existRow, true)
            }
        })
    })
}
const handleClose = () => {
    addShow.value = false
    getLists()
}
const itemdata = ref([
    {
        declarationTypeId: '122',
        andsqlName: ''
    }
]);

const handleRows = (items: any) => {
    itemdata.value = [];  // 清空之前的数据
    items.forEach(item => {
        // declarationTypeId
        // declarationTypeName
        itemdata.value.push(item);
        item['declarationTypeId'] = item.id
        console.log(item, '111111222')
    });

}


const handleSubmit = async () => {
    if (itemdata.value.length === 0) {
        feedback.msgWarning('请至少选择一项数据');
        return;
    }
    console.log(itemdata.value, '2222')
    let formattedList = itemdata.value
    // let formattedList = Object.values(itemdata.value).map(String);
    formData.declarationConditions = formattedList
    console.log("被选中的", formattedList);

    // const data={
    //     projetId:formData.id,
    //     declarationTypeIdList:formattedList
    // }
    //  await DetailTypeAddList(data);
    //  getLists();
    //  getDetail(formData.id)
    addShow.value = false

}
// 监听数据变化
watch(() => pager.lists.values, () => {
    if (addShow.value) {
        nextTick(() => {
            // 重新选中之前选中的项
            declarationConditionsList.value.forEach(row => {
                const existRow = pager.lists.find(item => item.id === row.declarationTypeId)
                if (existRow && myTable.value) {
                    myTable.value.toggleRowSelection(existRow, true)
                }
            })
        })
    }
})



getLists()
remoteLocationMethod()
</script>

<style scoped>
:deep(.el-tag__content) {
    display: inline-flex;
    /* 使用 inline-flex 来保证标签内的内容和删除图标在一行内 */
    max-width: 380px;
    /* 设置最大宽度 */
    white-space: nowrap;
    /* 防止换行 */
    overflow: hidden;
    /* 隐藏超出部分 */
    text-overflow: ellipsis;
    /* 显示省略号 */
    cursor: pointer;
    /* 鼠标悬停时显示手形光标 */
}
</style>